<?php

function sc_software_list() {
  global $user, $base_url;

  drupal_add_js('var baseUrl = "' . $base_url . '";', 'inline');
  drupal_add_js(drupal_get_path('module', 'sckeys') . '/js/sc_software_list.js');
  
  $header = array(
      t('Phần mềm'),
      t('Alias'),
      t('Ngày tạo'),
      t('User'),
      array('data' => t('Operations'), 'colspan' => 2),
  );

  $sc_softwares = db_select('sc_software', 'e')
          ->addTag('translatable')
          ->fields('e')
          ->orderBy('e.date_create', 'DESC')
          ->execute()
          ->fetchAll();

  $rows = array();
  if ($sc_softwares) {
    foreach ($sc_softwares as $sc_software) {
      $rows[] = array(
          l(t($sc_software->scs_name), 'shortcut-keys/' . $sc_software->scs_id . '/' . $sc_software->scs_alias),
          check_plain($sc_software->scs_alias),
          check_plain($sc_software->date_create),
          check_plain($sc_software->user_id),
          l(t('Sửa'), 'sc_soft/edit/' . $sc_software->scs_id),
          '<a onclick="removeSoftware(' . $sc_software->scs_id . '); return false;" href="#">Remove</a>'
      );
    }
  }

  if (!$rows) {
    $rows[] = array(array(
            'data' => t('Không có liên hệ nào được gửi đến bạn'),
            'colspan' => 8,
            ));
  }
  $build['send_form_table'] = array(
      '#theme' => 'table',
      '#header' => $header,
      '#rows' => $rows,
  );
  return $build;
}

function sc_software_add($form, &$form_state) {
  $id = arg(2);
  if ($id) {
    $scSoftware = sc_software_dbget($id);
    drupal_set_title($scSoftware->scs_name);
  }

  drupal_add_js(drupal_get_path('module', 'sckeys') . '/js/sc_software_add.js');

  $form['scs_name'] = array(
      '#type' => 'textfield',
      '#title' => t('Tên'),
      '#required' => TRUE,
      '#value' => isset($scSoftware) ? $scSoftware->scs_name : null,
      '#description' => t("Tên của phần mềm."),
      '#attributes' => array(
          'onkeyup' => array(
              'convertAlias();',
          ),
          'id' => 'scs_name',
      ),
  );
  $form['scs_alias'] = array(
      '#type' => 'textfield',
      '#required' => TRUE,
      '#value' => isset($scSoftware) ? $scSoftware->scs_alias : null,
      '#title' => t('Alias:'),
      '#attributes' => array(
          'id' => 'scs_alias',
      ),
  );
  $form['scs_id'] = array(
      '#type' => 'hidden',
      '#value' => isset($scSoftware) ? $scSoftware->scs_id : null,
  );


  $form['actions'] = array('#type' => 'actions');
  $form['actions']['submit'] = array(
      '#type' => 'submit',
      '#value' => 'Save',
  );

  return $form;
}

function sc_software_add_validate($form, &$form_state) {
  if (empty($form_state['input']['scs_name'])) {
    form_set_error('', t('Tên không được để trống.'));
  }

  if (empty($form_state['input']['scs_alias'])) {
    form_set_error('', t('Alias không được để trống.'));
  }
}

function sc_software_add_submit($form, &$form_state) {
  global $user;
  $form_state['input']['date_create'] = date('Y-m-d H:i:s', time());
  $form_state['input']['user_id'] = $user->uid;

  if (!empty($form_state['input']['scs_id'])) {
    drupal_write_record('sc_software', $values, array($form_state['input']['scs_id']));
  } else {
    $form_state['input']['scs_id'] = 0;
    drupal_write_record('sc_software', $form_state['input']);
  }

  drupal_goto('sc_soft/' . $form_state['input']['scs_id'] . '/sckeys_list');
}

function sc_software_dbget($id) {
  return db_select('sc_software', 'p')
                  ->fields('p')->condition('scs_id', $id)
                  ->execute()->fetch();
}

function sc_software_delete() {
  if ($_POST['ajax']) {
    $scs_id = arg(2);

    if (checkUserOwnerSck($sck_id)) {
      db_delete('sc_keys')
              ->condition('sck_id', $sck_id)
              ->execute();
      print 'success';
    } else {
      print 'failed';
    }
  }
}

function sc_keys_delete() {
  $sck_id = arg(2);

  if (checkUserOwnerSck($sck_id)) {
    db_delete('sc_keys')
            ->condition('sck_id', $sck_id)
            ->execute();
    print 'success';
  } else {
    print 'failed';
  }
}

function sc_keys_list() {
  global $base_url;
  drupal_add_js('var baseUrl = "' . $base_url . '"; var scsId = ' . arg(1) . ';', 'inline');
  drupal_add_js(drupal_get_path('module', 'sckeys') . '/js/main.js');

  $html_str = '<div id="keys-pager">' . sc_keys_table() . '</div>';

  return $html_str;
}

function ajax_load_keys() {
  print(sc_keys_table());
}

function sc_keys_table() {
  global $user;

  $scs_id = arg(1);

  $sc_keys = db_select('sc_keys', 'e')
          ->addTag('translatable')
          ->fields('e')
          ->condition('e.scs_id', $scs_id)
          ->condition('e.user_id', $user->uid)
          ->orderBy('e.sck_id', 'DESC')
          ->execute()
          ->fetchAll();

  $html_str = '';
  $html_str .= '
        <form id="from-keys">
          <table width="99%" id="tbl-keys">
            <thead>
              <th>Keys</th>
              <th>Descriptions</th>
              <th>Extentions</th>
              <th colspan="2">Operations</th>
            </thead>
            <tbody>';

  for ($i = 0; $i < 3; $i++) {
    $html_str .= '
                <tr class="row" id="row' . $i . '">
                  <td><input type="text" id="sck_key" name="sck_key[]"/></td>
                  <td><textarea type="text" id="sck_contents" name="sck_contents[]"></textarea></td>
                  <td></td>
                  <td colspan="2"></td>
                </tr>';
  }
  $html_str .= '
                <tr id="row-save">
                  <td colspan="4" align="right">
                  <button>Add More</button>
                  <button onclick="saveKey(' . $scs_id . '); return false;">Save</button>
                  </td>
                </tr>';

  if ($sc_keys) {
    foreach ($sc_keys as $sc_key) {
      $html_str .= '<tr id="row-' . $sc_key->sck_id . '">';
      $html_str .= '<td id="col-key">' . $sc_key->sck_key . '</td>';
      $html_str .= '<td id="col-contents">' . $sc_key->sck_contents . '</td>';
      $html_str .= '<td>' . $sc_key->video_id . '</td>';
      $html_str .= '<td id="col-operations">'
              . '<a onclick="editKey(' . $sc_key->sck_id . '); return false;" href="#">' . t('Edit') . '</a>&nbsp;&nbsp;'
              . '<a onclick="removeKey(' . $sc_key->sck_id . '); return false;" href="#">Remove</a>';
      $html_str .= '</td></tr>';
    }
  }
  $html_str .= '</tbody></table></form>';


  return $html_str;
}

function sc_keys_add() {
  dbinsert_keys($_POST);
  print 'success';
}

function sc_keys_update() {
  global $user;

  $sck_id = arg(2);

  if (checkUserOwnerSck($sck_id)) {
    db_update('sc_keys') // Table name no longer needs {}
            ->fields(array(
                'sck_key' => $_POST['sck_key'],
                'sck_contents' => $_POST['sck_contents'],
            ))
            ->condition('sck_id', $sck_id)
            ->condition('user_id', $user->uid)
            ->execute();

    print 'success';
  } else {
    print 'failed';
  }
}

function dbinsert_keys($values) {
  global $user;
  $sql = 'INSERT INTO {sc_keys} (scs_id, sck_key, sck_contents, user_id) VALUES ';
  $sql2 = '';

  for ($i = 0; $i < count($values['sck_key']); $i++) {
    if (trim($values['sck_key'][$i]) != '') {
      if (strlen($sql2)) {
        $sql2 .= ', ';
      }
      $sql2 .= "(" . $values['scs_id'] . ", '" . $values['sck_key'][$i] . "', '" . $values['sck_contents'][$i] . "', $user->uid)";
    }
  }

  if ($sql2 != '') {
    db_query($sql . $sql2);
    return true;
  }

  return false;
}


/*
 * Check user that created scs
 */

function checkUserOwnerScs($scs_id) {
  global $user;

  $check = db_select('sc_software', 'e')
          ->addTag('translatable')
          ->fields('e')
          ->condition('scs_id', $scs_id)
          ->condition('user_id', $user->uid)
          ->execute()
          ->fetchAssoc();
  if ($check)
    return true;

  return false;
}


/*
 * Check user that created sck
 */

function checkUserOwnerSck($sck_id) {
  global $user;

  $check = db_select('sc_keys', 'e')
          ->addTag('translatable')
          ->fields('e')
          ->condition('sck_id', $sck_id)
          ->condition('user_id', $user->uid)
          ->execute()
          ->fetchAssoc();
  if ($check)
    return true;

  return false;
}

?>